import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gczn_hd/app/core/base/base_controller.dart';
import 'package:gczn_hd/app/data/remote/gczn_remote_data_source.dart';
import 'package:gczn_hd/app/data/repository/gczn_repository.dart';
import 'package:gczn_hd/app/modules/login/model/login_model.dart';
import 'package:gczn_hd/app/modules/login/model/user_response.dart';
import 'package:gczn_hd/flavors/build_config.dart';
import 'package:gczn_hd/flavors/env_config.dart';
import 'package:gczn_hd/flavors/environment.dart';
import 'package:get/get.dart';

import '../../../data/local/preference/preference_manager.dart';
import '../../../routes/app_pages.dart';

class LoginController extends BaseController with GetSingleTickerProviderStateMixin{

  late GcznRepository _gcRequest;
  late PreferenceManager _preferenceManager;


  final EnvConfig config = BuildConfig.instance.config;

  final TextEditingController accountController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  RxBool isChecked = false.obs;

  final Rx<DateTime> lastPressedAt = DateTime.now().obs;

  onViewInit(){
    lastPressedAt.value = DateTime.now();
    _gcRequest = Get.find(tag: (GcznRepository).toString());
    _preferenceManager = Get.find(tag: (PreferenceManager).toString());

    // 开发环境
    // if( BuildConfig.instance.environment == Environment.DEVELOPMENT ){
    //   accountController.text = "tanghq";
    //   passwordController.text = "123456";
    // }
  }


  void login() async {

    LoginResponse data = await callDataService(
        _gcRequest.login(LoginRequest(account: accountController.text, password: passwordController.text)),
      isShowLoading: true
    );
    _preferenceManager.setString(PreferenceManager.keyToken, data.accessToken!);
    _preferenceManager.setString(PreferenceManager.keyTokenDataString,jsonEncode(data.toJson()));
    config.token = data.accessToken!;

    Fluttertoast.showToast(msg: "登录成功");

    UserResponse userData = await getUserInformation();
    _preferenceManager.setStringToObject(PreferenceManager.keyUserData, userData.toJson());

    Get.offAllNamed(Routes.HOME);


  }

  Future<UserResponse> getUserInformation() async {
    return await callDataService(_gcRequest.getUserMsg());
  }




  @override
  void onClose() {
    accountController.dispose();
    passwordController.dispose();
    super.onClose();
  }


}
